import 'dart:ui';

import 'package:flame/components.dart';
import 'package:flame/flame.dart';
import 'package:flame/sprite.dart';

class PlayerStateComponent extends SpriteAnimationComponent {
  Image? _image;
  SpriteSheet? _spriteSheet;
  Vector2? pSize;
  var currentState = PlayState.IDLE;



  PlayerStateComponent(Vector2 pSize) {
    this.pSize = pSize;
  }

  Future<void> initImage() async {
    print("加载图片");
    //加载图片
    _image = await Flame.images.load('sword_2x.png');
    print("_image=${_image!.width} * ${_image!.height}");
    // 创建 SpriteSheet
    _spriteSheet = SpriteSheet.fromColumnsAndRows(
      image: _image!,
      columns: 6,
      rows: 10,
    );
    scale = (Vector2(0.5, 0.5)); //整体缩放0.5倍
    var realSize = _spriteSheet!.srcSize * 0.5; //真实的每一帧的尺寸也需要缩放0.5倍
    print("1position=${position} pSize=$pSize");
    position = Vector2((pSize!.x - realSize.x) / 2, -pSize!.y);
    print("2position=${position} img=>${_spriteSheet?.srcSize}");
  }


  @override
  Future<void> onLoad() async {
    debugMode = true;
    return super.onLoad();
  }

  bool isIdle(){
    return currentState == PlayState.IDLE;
  }
  bool isAttack(){
    return currentState == PlayState.ATTACK;
  }
  bool isRun(){
    return currentState == PlayState.RUN;
  }

  void resetState() async {
    currentState = PlayState.IDLE;
  }
  void loadIdleState(double stepTime) async {
    if (_image == null) {
      await initImage();
    }
    currentState = PlayState.IDLE;
    _loadAnimation(stepTime, row: 0, from: 0, to: 5, loop: true);
  }

  void loadAttackState(double stepTime) async {
    if (_image == null) {
      await initImage();
    }
    if (currentState == PlayState.ATTACK) {
      return;
    }
    currentState = PlayState.ATTACK;
    _loadAnimation(stepTime, row: 1, from: 0, to: 5);
  }

  void loadRunState(double stepTime) async {
    if (_image == null) {
      await initImage();
    }
    if (currentState == PlayState.RUN) {
      return;
    }
    currentState = PlayState.RUN;
    _loadAnimation(stepTime, row: 2, from: 0, to: 5, loop: true);
  }

  void _loadAnimation(
    double stepTime, {
    int row = 0,
    int from = 0,
    int to = 1,
    bool loop = false,
  }) {
    // 创建动画组件
    animation = _spriteSheet?.createAnimation(
      row: row,
      stepTime: stepTime,
      from: from,
      to: to,
      loop: loop,
    );
    //print("$currentState 动作ing");
    animationTicker?.onComplete=(){
      if (currentState != PlayState.IDLE) {
        //print("$currentState 动作完成");
        loadIdleState(0.2);
      }
    };

    // if (currentState != PlayState.IDLE) {
    //   final ticker = animation?.createTicker();
    //   ticker?.onComplete = () {
    //     print("$currentState 动作完成");
    //     loadIdleState(0.2);
    //   };
    // }
    //addToParent(parent!);
  }

  @override
  void onRemove() {
    _image?.dispose();
  }
}

enum PlayState {
  IDLE,
  ATTACK,
  RUN,
}